#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "proc.h"

#ifdef __linux
const char *command = "ps -e -l | tr -s ' ' | cut -d\" \" -f\"4,5,14\"";
#elif defined __minix
const char *command = "ps -e -l | tr -s ' ' | cut -d\" \" -f\"4,5,9,10,11,12\"";
#endif

/**
 * Parses the ps command output and builds index
 * Returns size of the index
 */
int parse_ps()
{
	FILE *file = (FILE*)popen(command, "r");
	char line[100];
	proc_tree = (struct proc*) malloc(sizeof(struct proc));
	char *token, *cmd;
	fgets(line, 100, file); // Throw away first line
	int i=0;
	while (fgets(line, 100, file) != NULL) {
		token = strtok(line, " \n");
		proc_tree = (struct proc*)realloc(proc_tree, (i+1) * sizeof(struct proc));
		if (atoi(token) == 0) {
			sscanf(token, "(%d", &proc_tree[i].pid);
		}
		else { 
			proc_tree[i].pid = atoi(token);
		}
		token = strtok(NULL, " \n");
		proc_tree[i].ppid = atoi(token);
		token = strtok(NULL, " \n");
#ifdef __linux 
		memcpy(proc_tree[i].name, token, sizeof(proc_tree[i].name));
#elif defined __minix
		// Catch the last field in the record
		while (token != NULL) {
			cmd = token;
			token = strtok(NULL, " \n");
			if (token == NULL) {
				memcpy(proc_tree[i].name, cmd, sizeof(proc_tree[i].name));
			}
		}
#endif
		proc_tree[i].parent = proc_tree[i].child = proc_tree[i].sibling = -1;
		proc_tree[i].level = 0;
		i++;
	}
	fclose(file);

	return i; // Size of the index
}

